<?php
class BidAuctions extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @return Organizations the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'bid_auctions';
	}
	
	public function relations()
	{
		return array(
			'auction'=>array(self::BELONGS_TO, 'Auctions', 'auction_ID'),
			'user'=>array(self::BELONGS_TO, 'Users', 'user_ID'),
		);
	}
	
	public function rules()
	{
		return array(
			array('user_ID, auction_ID, fuel_cost_per_gallon, delivered_price_per_gallon', 'required', 'on'=>'create'),
			array('fuel_cost_per_gallon, freight_cost_per_gallon, ancillary_fees, fed_excise_tax, fed_lust, fed_oil_spill_fee, nc_road_tax, nc_wholesale, nc_inspection, nc_tare, delivered_price_per_gallon', 'numerical', 'min'=>0, 'numberPattern'=>'/^(\d{1,9})?+(\.\d{1,6})?$/', 'on'=>'create'),
			array('user_ID, auction_ID', 'unique', 'criteria' => array('select'=>$this->tableName(),
															'condition' => 'auction_ID=:auction_ID and user_ID=:user_ID',
															'params'=>array(':auction_ID'=>$this->auction_ID, ':user_ID'=>$this->user_ID),
															),
															'on'=>'create',
															'message'=>'The bid has already been placed by this user.',
														),
		);
	}
	
	public function getAuction($userID, $auctionID) {
		$sql = "SELECT * FROM ".$this->tableName()." WHERE user_ID='".$userID."' AND auction_ID='".$auctionID."'";
		$auction = $this->findAllBySql($sql);
		
		return $auction;
	}
	
	public function getMinPrice($auctionID)
	{
		$connection = Yii::app()->db;
		$sql='select user_ID, min(delivered_price_per_gallon) from '.$this->tableName().' where auction_ID='.$auctionID;
		$command = $connection->createCommand($sql);
		$dataReader = $command->query();
		foreach($dataReader as $row)
		{
			return array($row['user_ID'], $row['min(delivered_price_per_gallon)']);
		}
	}
}
?>